package com.gm.app.data;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;

import org.springframework.beans.factory.annotation.Configurable;

import com.gm.app.model.Register;

@Configurable
public class EntityDAO {

	private EntityManager entityManager;

	public EntityManager getEntityManager() {
		return entityManager;
	}

	@PersistenceContext
	public void setEntityManager(EntityManager entityManager) {
		this.entityManager = entityManager;
	}

	public <T> TypedQuery<T> query(String query, Class<T> clazz,
			Object... params) {
		TypedQuery<T> q = entityManager.createQuery(query, clazz);
		int i = 1;
		for (Object param : params) {
			q.setParameter(i++, param);
		}
		return q;
	}

	public <T> TypedQuery<T> pagedQuery(String query, Integer start,
			Integer page, Class<T> clazz, Object... params) {
		TypedQuery<T> q = query(query, clazz, params);
		if (start != null && start > 0) {
			q.setFirstResult(start);
			if (page != null && page > 0) {
				q.setMaxResults(page);
			}
		}
		return q;
	}

	public <T> TypedQuery<T> namedQuery(String name, Class<T> clazz,
			Object... params) {
		TypedQuery<T> q = entityManager.createNamedQuery(name, clazz);
		int i = 1;
		for (Object param : params) {
			q.setParameter(i, param);
		}
		return q;
	}

	protected static Map<StringBuilder, List<String>> getParts(String value,
			String template, boolean isFirst) {
		StringBuilder query = new StringBuilder();
		List<String> params = new ArrayList<String>();
		if (value != null && value.length() > 0) {
			String[] valueParts = value.split(" ");
			for (String part : valueParts) {
				if (isFirst) {
					isFirst = false;
				} else {
					query.append("AND ");
				}
				query.append(template);
				params.add("%" + part + "%");
			}
			if (query.length() == 0) {
				query.append(template);
				params.add(" ");
			}
		}
		Map<StringBuilder, List<String>> map = new HashMap<StringBuilder, List<String>>();
		map.put(query, params);
		return map;
	}
}
